package io.renren.modules.tree.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.tree.service.TreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author A夜兔A
 * @data 2021年11月19日 14:37
 */
@Service
public class TreeServiceImpl implements TreeService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public R getUserTree() {

        List<SysUserEntity> sysUserEntities = sysUserService.list(new LambdaQueryWrapper<SysUserEntity>()
                .ne(SysUserEntity::getUserId, 1));

        List<SysUserEntity> collect = sysUserEntities.stream()
                .filter(x -> x.getCreateUserId() == 1)
                .collect(Collectors.toList());


        for (SysUserEntity sysUserEntity : collect) {
            List<SysUserEntity> children = getChildren(sysUserEntity, sysUserEntities);
            sysUserEntity.setChildrenUsers(children);
        }

        return R.ok("操作完成").put("userTree",collect);
    }


    private static List<SysUserEntity> getChildren(SysUserEntity sysUserEntity,List<SysUserEntity> sysUserEntities){

        List<SysUserEntity> sysUserEntityList=new ArrayList<>();

        for (SysUserEntity userEntity : sysUserEntities) {

            if (userEntity.getCreateUserId()==sysUserEntity.getUserId()){
                sysUserEntityList.add(userEntity);
                getChildren(userEntity,sysUserEntities);
            }

        }
        sysUserEntity.setChildrenUsers(sysUserEntityList);

        return sysUserEntityList;
    }




}
